from datetime import datetime
from app.models.db_setup import db


class Cart(db.Model):
    __tablename__ = "Cart"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey("User.id"), nullable=False)
    product_id = db.Column(db.Integer, db.ForeignKey("Product.id"), nullable=False)
    sku_code = db.Column(db.String(50), nullable=True)  # SKU 编码
    quantity = db.Column(db.Integer, nullable=False, default=1)
    selected = db.Column(db.Boolean, default=True)  # 是否被选中
    created_at = db.Column(db.DateTime, server_default=db.func.now())

    # 关联关系
    user = db.relationship("User", backref=db.backref("cart_items", lazy=True))
    product = db.relationship("Product", backref=db.backref("cart_items", lazy=True))

    def __init__(
        self, user_id, product_id, sku_code=None, quantity=1, selected=True
    ):
        self.user_id = user_id
        self.product_id = product_id
        self.sku_code = sku_code
        self.quantity = quantity
        self.selected = selected

    def to_dict(self):
        # 获取产品数据
        product_data = self.product.to_dict() if self.product else None

        # 获取当前SKU的价格和规格信息
        sku_data = None
        specifications = {}
        sale_price = None
        list_price = None

        if product_data and "skus" in product_data and self.sku_code:
            for sku in product_data["skus"]:
                if sku.get("skuCode") == self.sku_code:
                    sku_data = sku
                    sale_price = float(sku.get("salePrice", 0))
                    list_price = float(sku.get("listPrice", sale_price))

                    # 提取规格信息
                    if "length" in sku:
                        specifications["length"] = sku["length"]
                    if "diameter" in sku:
                        specifications["diameter"] = sku["diameter"]
                    if "pearlSize" in sku:
                        specifications["pearlSize"] = sku["pearlSize"]
                    if "pearlColor" in sku:
                        specifications["pearlColor"] = sku["pearlColor"]
                    break

        # 简化的产品信息
        simple_product = {
            "id": product_data["id"] if product_data else None,
            "name": product_data["name"] if product_data else None,
            "preview_image_url": (
                product_data["preview_image_url"] if product_data else None
            ),
            "category": product_data["category"] if product_data else None,
        }

        return {
            "id": self.id,
            "product": simple_product,
            "skuCode": self.sku_code,
            "salePrice": sale_price,
            "listPrice": list_price,
            "selected": self.selected,
            "specifications": specifications,
            "quantity": self.quantity,
            "created_at": self.created_at.isoformat() if self.created_at else None,
        }
